package com.anjbo.controller.loan;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.anjbo.common.Constants;
import com.anjbo.common.RespDataObject;
import com.anjbo.common.RespStatusEnum;
import com.anjbo.service.loan.CgbMortgageService;
import com.anjbo.service.order.OrderThirdService;
import com.anjbo.service.system.UserMortService;
import com.anjbo.utils.AmsUtil;
import com.anjbo.utils.ConfigUtil;
import com.anjbo.utils.LoginCacheUtil;
import com.anjbo.utils.UidUtil;

@Controller
@RequestMapping(value = "/app/loan/mortgage/cgb")
public class CgbMortgageController {

	private static Log log = LogFactory.getLog(CgbMortgageController.class);

	@Resource
	private OrderThirdService orderThirdService;
	@Resource
	private UserMortService userMortService;

	@Resource
	private CgbMortgageService cgbMortgageService;

	@RequestMapping("/addOrder")
	@ResponseBody
	public RespDataObject<Map<String, Object>> addOrder(HttpServletRequest request, @RequestBody Map<String, Object> param) {
		RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
		Map<String, Object> orderInfo = new HashMap<String, Object>();

		String uid = MapUtils.getString(param, "uid");
		if(uid==null||"".equals(uid)){
			String sid = (String) request.getHeader("sid");
			String deviceId = (String) request.getHeader("deviceId");
			
			uid = LoginCacheUtil.getUid(sid, deviceId);
		}
		
		param.put("uid", uid);
		String orderNo = UidUtil.generateOrderId();// 唯一orderNO
		param.put("orderNo", orderNo);

		// 判断一天三次
		int cgbTimesLimit = ConfigUtil.getIntegerValue("cgb_times_limit");
		if(cgbTimesLimit==0){
			cgbTimesLimit=3;
		}
		int count = cgbMortgageService.selectCgbCountByUid(param);
		if (count >= cgbTimesLimit) {
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg("您今天申请的次数已达到3次，请明天再试。");
			return resp;
		}

		try {
			// 获取广发抵押贷初始节点信息
			Map<String, Object> progress = cgbMortgageService.getCgbMortgageFirstProgress();
			param.put("progressId", MapUtils.getString(progress, "progressId"));
			orderInfo.put("progressName", MapUtils.getString(progress, "progressName"));

			// 保存订单
			cgbMortgageService.insertCgbMortgage(param);
			
			// 保存订单初始状态
			cgbMortgageService.insertCgbMortgageProgress(param);

			// 发送短信
			sendMessage(param);

		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}

		// 存入第三方订单表
		String pawnType=MapUtils.getInteger(param, "pawnType").toString();
		String name="";
		if("1".equals(pawnType)){
			name="住宅";
		}else if("2".equals(pawnType)){
			name="非住宅";
		}
		
		orderInfo.put("uid", uid);
		orderInfo.put("type", 15);
		orderInfo.put("orderNo", orderNo);
		orderInfo.put("name", name);
		orderInfo.put("loanAmount", MapUtils.getString(param, "loanAmount"));
		orderInfo.put("progressId", MapUtils.getString(param, "progressId"));
		orderInfo.put("certificateNo", "");

		int third = orderThirdService.add(orderInfo);
		if (third <= 0) {
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}
		
		resp.setData(orderInfo);
		resp.setCode(RespStatusEnum.SUCCESS.getCode());
		resp.setMsg(RespStatusEnum.SUCCESS.getMsg());

		return resp;
	}

	/**
	 * 获取订单详情（广发抵押贷）
	 * @param request
	 * @param param
	 * @return
	 */
	@RequestMapping("/getOrderDetail")
	@ResponseBody
	public RespDataObject<Map<String, Object>> getOrderDetail(HttpServletRequest request,@RequestBody Map<String, Object> param) {
		RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
		Map<String, Object> orderInfo = new HashMap<String, Object>();
		
		try {
			orderInfo = cgbMortgageService.getCgbMortgageByOrderNo(param);
			List<Map<String,Object>> progressList = cgbMortgageService.selectCgbOrderProgressList();
			orderInfo.put("progressList", progressList);
			
			//将progressId 由int转String
			Integer progressId = MapUtils.getInteger(orderInfo, "progressId");
			Integer state = MapUtils.getInteger(orderInfo, "state");
            if(progressId!=null){
            	orderInfo.put("progressId", progressId.toString());
            }
            if(progressList!=null&&progressList.size()>0){
            	for(Map<String, Object> progressMap : progressList){
            		Integer id = MapUtils.getInteger(progressMap, "progressId");
            		if(id!=null){
            			if(progressId != null &&progressId.equals(id)&&state==2){
            				progressMap.put("progressName", MapUtils.getString(progressMap, "progressName")+"失败");
            			}
            			progressMap.put("progressId", id.toString());
                    }
            		
            	}
            }
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode(RespStatusEnum.FAIL.getCode());
			resp.setMsg(RespStatusEnum.FAIL.getMsg());
			return resp;
		}
		
		resp.setData(orderInfo);
		resp.setCode(RespStatusEnum.SUCCESS.getCode());
		resp.setMsg(RespStatusEnum.SUCCESS.getMsg());
		
		return resp;
	}

	private void sendMessage(Map<String, Object> param) {
		String mobile = ConfigUtil.getStringValue("cgb_msg_phone");
		if(mobile==null||"".equals(mobile)){
			mobile="13712999868";
		}
		
		String loanType = MapUtils.getInteger(param, "loanType").toString();
		String pawnType = MapUtils.getInteger(param, "pawnType").toString();

		StringBuffer sb = new StringBuffer("广发抵押贷，基本信息如下。");

		sb.append("客户姓名：" + MapUtils.getString(param, "name"));

		if ("1".equals(loanType)) {
			sb.append("；贷款类型：经营贷");
		} else if ("2".equals(loanType)) {
			sb.append("；贷款类型：消费贷");
		}

		sb.append("；贷款金额：" + MapUtils.getString(param, "loanAmount") + "万");

		if ("1".equals(pawnType)) {
			sb.append("；抵押物类型：住宅");
		} else if ("2".equals(pawnType)) {
			sb.append("；抵押物类型：非住宅");
		}

		sb.append("；抵押物地址：" + MapUtils.getString(param, "pawnAddress"));
		sb.append("；客户联系电话：" + MapUtils.getString(param, "phone")+"。");
		try {
			AmsUtil.smsSendNoLimit(mobile, "app", sb.toString(), Constants.SMS_FLAG_3);
		} catch (Exception e) {
			log.info("广发抵押贷短信发送失败:" + e.getMessage());
		}
	}

}
